import json
import boto3
from boto3.dynamodb.conditions import Key, Attr


def lambda_handler(event, context):
    # TODO implement

    dynamodb = boto3.resource('dynamodb')

    passcode_table = dynamodb.Table('passcodes')
    visitor_table = dynamodb.Table('visitors')

    otp = int(event['body'][9:])
    # print(otp)

    # # check if otp in passcode_table
    response = passcode_table.scan(
        FilterExpression=Attr('otp').eq(otp)
    )

    # if not found
    if len(response['Items']) == 0:
        return {
            'statusCode': 400,
            'body': json.dumps('Invalid otp!')
        }

    # if found, retrieve visitor information
    faceId = response['Items'][0]['faceId']
    passcode_table.delete_item(
        Key={
            'otp': otp
        }
    )

    result = visitor_table.scan(
        FilterExpression=Attr('faceId').eq(faceId)
    )
    name = result['Items'][0]['name']

    return {
        'statusCode': 200,
        'body': json.dumps('Hello from smart door! ' + name)
    }
